#include "translation.h"
#include <QApplication>
#include <QCoreApplication>
#include <QSettings>
#include "confighandler.h"
#include <enum_file.h>
#include "log.h"

Translation::Translation(QQuickView *view)
{
    m_view = view;
    m_translator = new QTranslator(this);
    reloadFontFimily(0);
    initLanguage();
}

Translation::~Translation()
{}

void Translation::initLanguage()
{
    int language = GlobalConfig::GetInstance()->readConfig(CommonEnum::LAUNCH_LANGUAGE).toInt();
    changedSystemLanguage(language);
}

void Translation::updateLanguage(int language)
{
    changedSystemLanguage(language);
}

void Translation::changedSystemLanguage(int language)
{
    QString logStr = QString("Translation::changedSystemLanguage, language = %1").arg(language);
    Log::writeDate(logStr);

    qApp->removeTranslator(m_translator);
    GlobalConfig::GetInstance()->writeConfig(CommonEnum::LAUNCH_LANGUAGE, language).toInt();

    if(language == 1) {
        m_translator->load(":/languages/languages/translation_zh.qm", ".");
    }else if(language == 0){
        m_translator->load(":/languages/languages/translation_en.qm", ".");
    }

    //reload font
//#ifdef Q_OS_WIN
    //reloadFontFimily(language);
//#endif

    qApp->installTranslator(m_translator);
    m_view->rootContext()->engine()->retranslate();
    emit languageChanged();
}

void Translation::reloadFontFimily(int language)
{
    //Font: Alibaba PuHuiTi 3.0
    QFontDatabase::addApplicationFont(":/font/assets/font/AlibabaPuHuiTi/AlibabaPuHuiTi-3-Thin.otf");
    QFontDatabase::addApplicationFont(":/font/assets/font/AlibabaPuHuiTi/AlibabaPuHuiTi-3-45-Light.otf");
    QFontDatabase::addApplicationFont(":/font/assets/font/AlibabaPuHuiTi/AlibabaPuHuiTi-3-55-Regular.otf");
    QFontDatabase::addApplicationFont(":/font/assets/font/AlibabaPuHuiTi/AlibabaPuHuiTi-3-55-RegularL3.otf");
    QFontDatabase::addApplicationFont(":/font/assets/font/AlibabaPuHuiTi/AlibabaPuHuiTi-3-65-Medium.otf");
    QFontDatabase::addApplicationFont(":/font/assets/font/AlibabaPuHuiTi/AlibabaPuHuiTi-3-75-SemiBold.otf");
    QFontDatabase::addApplicationFont(":/font/assets/font/AlibabaPuHuiTi/AlibabaPuHuiTi-3-85-Bold.otf");
    QFontDatabase::addApplicationFont(":/font/assets/font/AlibabaPuHuiTi/AlibabaPuHuiTi-3-95-ExtraBold.otf");
    QFontDatabase::addApplicationFont(":/font/assets/font/AlibabaPuHuiTi/AlibabaPuHuiTi-3-105-Heavy.otf");
    QFontDatabase::addApplicationFont(":/font/assets/font/AlibabaPuHuiTi/AlibabaPuHuiTi-3-115-Black.otf");

    QString sansCNFamily = "Alibaba PuHuiTi 3.0";
    setFamily(sansCNFamily);
    QFont defaultFont(sansCNFamily);
    QApplication::setFont(defaultFont);
}

const QString &Translation::family() const
{
    return m_family;
}

void Translation::setFamily(const QString &newFamily)
{
    if (m_family == newFamily)
        return;
    m_family = newFamily;
    emit familyChanged();
}
